package com.example.messangersms;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseConnection extends SQLiteOpenHelper{
	
	//Database constructor
	public DatabaseConnection(Context context) {
		super(context, "AndroidMessengerG5", null, 1);
	}
	
	public ArrayList<Message> getMessages(int recipientId){
		ArrayList<Message> messages = new ArrayList<Message>();
		String statement = "SELECT * FROM Message WHERE RecipientId=\""+recipientId+"\"";
		
		SQLiteDatabase database = this.getWritableDatabase();
		Cursor cursor = database.rawQuery(statement,null);
		if(cursor.moveToFirst())
		{
			do{
				Message msg = new Message(cursor.getInt(2), cursor.getString(3));
				messages.add(msg);
			} while(cursor.moveToNext());
		}
		return messages;
	}
	//Basic user insert
		public void insertMessage(int recipientId, int senderId, String message){
			ContentValues newMessage = new ContentValues();
			newMessage.put("RecipientId", recipientId);
			newMessage.put("SenderId", senderId);
			newMessage.put("Message", message);
			
			SQLiteDatabase database = this.getWritableDatabase();
			database.insert("Message", null, newMessage);	
			database.close();
		}
		
	// This method will create the database if it doesn't exist
	@Override
	public void onCreate(SQLiteDatabase database) {
		
		String messageTable = "CREATE TABLE IF NOT EXISTS 'Message'(" +
				"MessageId INTEGER," +
				"RecipientId INTEGER NOT NULL,"+
				"SenderId INTEGER NOT NULL," +
				"Message VARCHAR(1000) NOT NULL"+
				");";
		
		database.execSQL(messageTable);
	}
	// This method specifies how to upgrade the database with a new version
	// of the application if necessary
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
	
	
}





